import atom.service
import gdata.service
import gdata.urlfetch
import time
import urllib
from google.appengine.api import urlfetch 
import gdata.health
import gdata.health.service
import simplejson
import logging

class GoogleHealthCCRReader(object):
    def __init__(self, profile_feed):
        self.profile_feed = profile_feed
    
    def get_medications(self):
        data_list = []
        for entry in self.profile_feed.entry:
            medications = entry.ccr.GetMedications()
            if medications:
                for med in medications: #med.ToString()
                    data = {}
                    
                    Product = med.FindChildren('Product')[0]
                    
                    data['name'] = Product.FindChildren('ProductName')[0].FindChildren('Text')[0].text
                    
                    for dt in med.FindChildren('DateTime'):
                        type = dt.FindChildren('Type')[0].FindChildren('Text')[0].text
                        date = dt.FindChildren('ExactDateTime')[0].text
                        if (type == "Start date"):
                            data['from'] = date
                        elif (type == "Stop date"):
                            data['to'] = date
                        elif (type == "Prescription date"):
                            data['written_on'] = date
                    
                    for sr in Product.FindChildren('Strength'):
                        data['pill_strength'] = sr.FindChildren('Value')[0].text
                        for un in sr.FindChildren('Units'):
                            data['pill_strength'] += ' ' + un.FindChildren('Unit')[0].text
                    
                    for ds in med.FindChildren('Directions'):
                        for di in ds.FindChildren('Direction'):
                            for do in ds.FindChildren('Dose'):
                                data['dosage'] = do.FindChildren('Value')[0].text
                            for fr in di.FindChildren('Frequency'):
                                data['frequency'] = fr.FindChildren('Value')[0].text
                            for ro in di.FindChildren('Route'):
                                data['route'] = ro.FindChildren('Text')[0].text
                    
                    for rs in med.FindChildren('Refills'):  
                        data['refills_left'] = rs.FindChildren('Refill')[0].FindChildren('Number')[0].text
                    
                    for ss in med.FindChildren('Source'):
                        for sc in ss.FindChildren('Actor'):
                            ro = sc.FindChildren('ActorRole')[0].FindChildren('Text')[0].text
                            if (ro == "Prescribing clinician"):
                                data['written_by'] = sc.FindChildren('ActorID')[0].text
                    
                    data['fulfillments'] = []
                    for fh in med.FindChildren('FulfillmentHistory'):
                        for ff in fh.FindChildren('Fulfillment'):
                            ff_data = {}
                            ff_data['quantity'] = ff.FindChildren('Quantity')[0].FindChildren('Value')[0].text
                            for ds in ff.FindChildren('IDs'):
                                ff_data['type'] = ds.FindChildren('Type')[0].FindChildren('Text').text
                                ff_data['id'] = ds.FindChildren('ID')[0].text
                            for dt in ff.FindChildren('DateTime')[0]:
                                type = dt.FindChildren('Type')[0].FindChildren('Text')[0].text
                                date = dt.FindChildren('ExactDateTime')[0].text
                                if (type == "Dispense date"):
                                    ff_data['filled_on'].append(date)
                                    data['fulfillments'].append(ff_data)
                    if not data['fulfillments']:
                        del data['fulfillments']
                    
                    data_list.append(data)
                    
        return data_list
    
    def get_immunizations(self):
        data = {}  
        return data

    def get_procedures(self):
        data = {}  
        return data

    def get_test_results(self):
        data = {}  
        return data
        
    def get_demographics(self):
        data = {}  
        return data

    def get_conditions(self):
        data_list = []
        for entry in self.profile_feed.entry:
            conditions = entry.ccr.GetProblems()
            #logging.info("Conditions:%s"%conditions)
            if conditions:
                for condition in conditions:
                    data = {}
                    data['status'] = condition.FindChildren('Status')[0].FindChildren('Text')[0].text 
                    # Dates
                    dates = condition.FindChildren('DateTime') #can be two
                    for date in dates:
                        logging.info("Date is %s"%date)
                        if date.FindChildren('Type')[0].FindChildren('Text')[0].text == "Start date":
                            data['start_date'] = date.FindChildren('ExactDateTime')[0].text
                        elif date.FindChildren('Type')[0].FindChildren('Text')[0].text == "Stop date":
                            data['end_date'] = date.FindChildren('ExactDateTime')[0].text
                        else:
                            data['other_date'] = date.FindChildren('ExactDateTime')[0].text 
                    # Description
                    desc = condition.FindChildren('Description')[0]  
                    data['name'] = desc.FindChildren('Text')[0].text
                    if desc.FindChildren('Code'):
                        data['code'] = desc.FindChildren('Code')[0].FindChildren('Value')[0].text
                        if desc.FindChildren('Code')[0].FindChildren('CodeSystem'):
                            data['code_system'] = desc.FindChildren('Code')[0].FindChildren('CodeSystem')[0].text
                        if desc.FindChildren('Code')[0].FindChildren('Version'):
                            data['code_version'] = desc.FindChildren('Code')[0].FindChildren('Version')[0].text
                    #Source subelement
                    actor = condition.FindChildren('Source')[0].FindChildren('Actor')[0]
                    data['treated_by'] = actor.FindChildren('ActorID')[0].text
                    if actor.FindChildren('ActorRole')[0].text:  
                       data['actor_role'] = actor.FindChildren('ActorRole')[0].text
                #logging.info(data)
                data_list.append(data)
        return data_list

#   def get_user_ccr(self):
#       json = dict([('results', []), ('error', {})]) 
#       for entry in self.profile_feed.entry:
#           try:
#             results = entry.ccr
#             for result in results:
#               test = result.FindChildren('Test')[0]
#               name = test.FindChildren('Description')[0].FindChildren('Text')[0].text
#               value = test.FindChildren('TestResult')[0].FindChildren('Value')[0].text
#               unit = test.FindChildren('TestResult')[0].FindChildren('Units')[0].FindChildren('Unit')[0].text
#               date = test.FindChildren('DateTime')[0].FindChildren('ExactDateTime')[0].text
#               row =  {'name': name, 'value': value, 'unit': unit, 'date': date}
#               json['results'].append(row)
#               logging.info("Found CCR entry:%s " % (row))
#           except Exception, e:
#             json['error'] = 'Could not find one or more CCR elements. %s'%e             
#       return json 
                    
#   def get_user_ccr_raw(self):
#       json = dict([('results', []), ('error', {})])
#       for entry in self.profile_feed.entry:
#           try:
#             results = entry.ccr
#             logging.info("Found CCR entry:%s " % (results))        
#             json['results'].append(results.GetMedications()) 
#             json['results'].append(results.GetImmunizations())
#             json['results'].append(results.GetAlerts())
#             json['results'].append(results.GetResults())
#             json['results'].append(results.GetProblems())
#             json['results'].append(results.GetProcedures()) 
#           except Exception, e:
#             json['error'] = 'Could not find one or more CCR elements. %s' % e
#       return json